package com.sky.web.app;


import com.sky.context.UserHolder;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
public class AppAddressBookController {


    @Autowired
    private AddressBookService addressBookService;

    //查询当前登录用户的所有地址信息
    @GetMapping("/list")
    public Result findList(){
        //1.获取登录人id
        Long userId = UserHolder.get();
        AddressBook addressBook = new AddressBook();
        //1-1封装登录人id,调用Service查询
        addressBook.setUserId(userId);
        List<AddressBook> list =addressBookService.findList(addressBook);
        //返回
        return Result.success(list);
    }

    //新增地址
    @PostMapping
    public Result save(@RequestBody  AddressBook addressBook){
        addressBookService.save(addressBook);
        return Result.success();
    }

    //设置默认地址
    @PutMapping("/default")
    public Result setDefault(@RequestBody AddressBook addressBook){
        addressBookService.setDefault(addressBook);
        return Result.success();
    }

    //查询默认地址
    @GetMapping("/default")
    public Result findDefault(){
        //1.获取登录人id
        Long userId = UserHolder.get();
        //2.封装查询条件
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(1);
       //3.调用Service查询
        List<AddressBook> list = addressBookService.findList(addressBook);
        if (list!=null) {
            return Result.success(list.get(0));
        }
        return Result.success("无默认地址");
    }


    //回显地址
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Long id) {
        AddressBook addressBook = addressBookService.findById(id);
        return Result.success(addressBook);
    }

    //修改地址
    @PutMapping
    public Result update(@RequestBody AddressBook addressBook) {
        addressBookService.update(addressBook);
        return Result.success();
    }

    //删除地址
    @DeleteMapping
    public Result delete(Long id) {
        addressBookService.deleteById(id);
        return Result.success();
    }


}
